﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Scheduler
{
    public class Worker
    {
        private object _id;

        private readonly List<Middleware> _middlewares = new List<Middleware>();

        private readonly WorkerTaskScheduler WorkerTaskScheduler = new WorkerTaskScheduler();
        public Worker(object id)
        {
            _id = id;
        }
        public Expression Right { get; set; }
        //  表示二元运算的左的操作数。
        public Expression Left { get; set; }
        ~Worker()
        {
            WorkerTaskScheduler.Dispose();
        }

        public void AddMiddleware(Middleware middleware)
        {
            if (middleware == null) return;
 
            //var index = _middlewares.FindIndex(m => m.Priority() < middleware.Priority());
   
        
            _middlewares.Insert(   0, middleware);
        }

        public Task Run(Context context)
        {
            Task t = new Task(() =>
            {
                while (true)
                {
                    var next = context.Next(_id);
                    if (next == null) return;
                    EmitEvent(context, new EventArgs(EventId.Handle, _id, next));
                 
                }
            });

            t.Start(WorkerTaskScheduler);
            return t;




            //while (context.Next(St) != null)
            //    EmitEvent(context, new EventArgs(EventId.Handle, _id));
        }

        public void EmitEvent(Context context, EventArgs args)
        {
            foreach (var m in _middlewares)
                m.HandleEvent(context, args);
        }

        public bool ShouldSkipThisPass(Context context) => context.ShouldSkipWorker(_id);


        public  bool Match()
        {
           /// return Left.Match() && Right.Match();
           return true;
        }

    }
}